package com.csf.struct.flyweight;

import java.util.Vector;

/**
 * TODO ADD DESCRIPTION
 * Date: 2018/9/6
 * Time: 17:50
 *
 * @author chenshf
 */
public class ConnectionPool {

    private int size = 100;

    private Vector<Connection> pool = null;

    /**
     * 初始化连接池
     */
    public ConnectionPool() {
        pool = new Vector<>(size);
        for (int i = 0; i < size; i++) {
            Connection connection = new Connection();
            pool.add(connection);
        }
    }

    /**
     * 从连接池获取一个连接
     *
     * @return
     */
    public Connection getConnection() {
        Connection connection = null;
        if (pool.size() > 0) {
            connection = pool.get(0);
            pool.remove(0);
        }
        return connection;
    }

    /**
     * 返回到连接池
     */
    public void release(Connection connection) {
        pool.add(connection);
    }
}
